package com.springboot.hotel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.hotel.model.SysMenu;
import com.springboot.hotel.model.SysUser;
import com.springboot.hotel.service.SysMenuService;
import com.springboot.hotel.mapper.SysMenuMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author 12641
* @description 针对表【sys_menu(菜单表)】的数据库操作Service实现
* @createDate 2023-06-16 15:47:07
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService{

    @Override
    public List<SysMenu> getAllMenusByTree() {
        // 查询所有的一级菜单
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",0);
        List<SysMenu> menus = list(wrapper);

        for (SysMenu menu : menus) {
            // 查询系统管理下的子菜单
            QueryWrapper<SysMenu> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("parent_id",menu.getId());
            List<SysMenu> list = list(wrapper1);
            menu.setChildren(list);
        }

        return menus;
    }

    @Override
    public List<SysMenu> getAllMenusByTree2() {
            QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
            wrapper.orderByAsc("parent_id","order_num");
//            所有菜单
        List<SysMenu> menus = list(wrapper);
        List<SysMenu> result = new ArrayList<>();
//        构建菜单树
        for(SysMenu menu:menus){
//        查询子菜单
            if (menu.getParentId()==0){
                List<SysMenu> children = getChildren(menu,menus);
                menu.setChildren(children);
                result.add(menu);
            }
        }
        return result;
    }
    private List<SysMenu> getChildren(SysMenu parentMenu,List<SysMenu> menus){
        List<SysMenu> children = new ArrayList<>();
        for (SysMenu sysMenu : menus){
            if (sysMenu.getParentId().equals(parentMenu.getId())){
                List<SysMenu> subChildren = getChildren(sysMenu,menus);
                sysMenu.setChildren(subChildren );
                children.add(sysMenu);
            }
        }
        return children;
    }
}




